<?php

namespace nimo\common\develop;

use DB;
use Log;
use Request;
use App;

class Profiler {
    private $times = array();
    public function __construct($start) {
        $this->times['boot'] = $start;
    }
    public function pass($name) {
        if (! isset($this->times[$name])) {
            $this->times[$name] = microtime(true);
        }
    }
    public function render() {
        $config = app('config');
        if ($config['app.debug'] != true) {
            return '';
        }

        $logs = array('----------------');
        $s = "generated ";
        $keys = array_keys($this->times);
        for($i = 0, $max = count($keys) - 1; $i < $max; $i ++) {
            $runtime = number_format(($this->times[$keys[$i + 1]] - $this->times[$keys[$i]]) * 1000, 2);
            $s = $s . ' ' . $keys[$i] . '[' . $runtime . '] ';
        }
        $runtime = 0;
        foreach ( DB::getQueryLog() as $query ) {
            $runtime += $query['time'];
        }
        $s = $s . 'query[' . $runtime . '] ';
        $runtime = number_format((microtime(true) - $this->times[$keys[0]]) * 1000, 2);
        $s = $s . 'total[' . $runtime . '] msec';
        $logs[] = $s;
        if ($config['app.showinclude']) {
            foreach ( get_included_files() as $file ) {
                $logs[] = $file;
            }
        }
        if ($config['app.showsql']) {
            foreach ( DB::getQueryLog() as $query ) {
                $logs[] = $query['query'];
            }
        }
        $logs[] = '----------------';
        Log::info(implode("\n", $logs));
        if (Request::ajax()) {
            return '';
        }
        if (App::runningInConsole()) {
            return implode("\n", $logs);
        }
        return "<ul> <li>" . implode("</li> \n <li>", $logs) . "</li></ul>";
    }
    public static function runtime($callback, $msg = null) {
        $startMem = memory_get_usage();
        $start = microtime(true);
        $result = $callback();
        $runtime = number_format((microtime(true) - $start) * 1000, 2);
        $memory = intval((memory_get_usage() - $startMem) / 1024);
        if ($msg) {
            echo ("$msg runtime=$runtime msec memory=$memory KB\n");
        } else {
            echo ("runtime=$runtime msec memory=$memory KB\n");
        }
        return $result;
    }

    public static function debug($ignore=2, $include=false, $deep = 5) {
        $config = app('config');
        if (! $config['app.showcallback']) {
            return null;
        }
        $trace = '';
        foreach (debug_backtrace() as $k => $v) {
            if ($k < $ignore ) { continue; }
            if ($k > $deep ) { break; }
            //array_walk($v['args'], function (&$item, $key) { $item = var_export($item, true);});
            $file = (isset($v['file'])? $v['file']:'');
            $line = (isset($v['line'])? '('.$v['line'].')':'');
            $class = (isset($v['class'])? $v['class']:'');
            $function = (isset($v['function'])? '::'.$v['function']:'');
            $args = $include ? "\n".str_replace(array("\r\n","\r","\n"), '', var_export($v['args'],true)) : '';
            $trace .= '#'.($k - $ignore)." $file $line $class$function $args\n";
        }
        Log::info($trace);
        return $trace;
    }
}
